const https = require("https");
const jsonpath = require("jsonpath");
const items = require("../mock/proxy.json");
const Proxy = require("http-mitm-proxy").Proxy;
const config = require("../config/index");
const bus = require("./bus");
const _ = require("lodash");
function findPorxyItem(url) {
  return items[url];
}

const proxy = new Proxy();
proxy.onError(function () {
  console.log("error");
});

proxy.onRequest(function (ctx, callback) {
  const url =
    ctx.clientToProxyRequest.headers.origin + ctx.clientToProxyRequest.url;
  const item = findPorxyItem(url);
  bus.emit("request", url);
  ctx.use(Proxy.gunzip);
  if (item) {
    ctx.onResponseData((ctx, chunk, callback) => {
      const json = JSON.parse(chunk.toString());
      // return callback(null, Buffer.from('sss'))
      // const contentType = ctx.serverToProxyResponse.headers['content-type']
      // if (contentType && contentType.includes('text/html')) {
      //     chunk = Buffer.from(`<script>console.log("脚本注入前")</script>`+chunk.toString()+`<script>console.log("脚本注入后")</script>`);

      // }
      // let data = {}
      try {
        Object.keys(item.modify).forEach((key) => {
          jsonpath.apply(json, key, (value) => {
            const val = item.modify[key];
            const findValue = jsonpath.query(json,val,1)[0]
            console.log('设置',key,findValue)
            return findValue||item.modify[key]//.replace(`{value}`, value);
          });
        });
       
      } catch (error) {
        console.log('errorerror=',error)
      }
      return callback(null, Buffer.from(JSON.stringify(json)));
    });
  }

  callback();
});

function createProxy(callback) {
  proxy.listen(
    {
      port: config.proxyPort,
      host: config.proxyHost,
      sslCaDir: config.sslCaDir,
    },
    callback
  );
}

module.exports = {
  createProxy,
};
